package com.stock.calculator.helper;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.stock.calculator.utils.URLHttpConnect;

public class FederalNoteHelper {

    private static final String DAILY_YIELD_CURVE_RATES_URL = "http://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield";

    private static String[][]   dailyYieldCurveRateTable;

    public static String fetchLatest10YrYieldCurveRate() throws IOException {
        String[][] dailyYieldCurveRateTable = fetchDailyYieldCurveRateTable();

        return dailyYieldCurveRateTable[dailyYieldCurveRateTable.length-1][9];
    }

    public static String[][] fetchDailyYieldCurveRateTable() throws IOException {
        if (dailyYieldCurveRateTable != null)
            return dailyYieldCurveRateTable;

        String response = URLHttpConnect.httpGet(DAILY_YIELD_CURVE_RATES_URL);

        String[] lines = response.split("\n");

        String[][] dailyYieldCurveRateTable = null;

        for (String line : lines) {
            if (line.contains("table") && line.contains("t-chart")) {

                Document doc = null;
                try {
                    doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(new InputSource(new StringReader(line)));
                    doc.getDocumentElement().normalize();

                } catch (SAXException e) {
                    e.printStackTrace();
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                }

                NodeList nodes = doc.getFirstChild().getChildNodes();

                dailyYieldCurveRateTable = new String[nodes.getLength()][];
                for (int i = 0; i < nodes.getLength(); ++i) {
                    NodeList childNodes = nodes.item(i).getChildNodes();

                    dailyYieldCurveRateTable[i] = new String[childNodes.getLength()];
                    for (int j = 0; j < childNodes.getLength(); ++j)
                        dailyYieldCurveRateTable[i][j] = childNodes.item(j).getFirstChild().getNodeValue();

                }
            }
        }

        return dailyYieldCurveRateTable;
    }

}
